package xin.nick.common.core.interceptor;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import xin.nick.common.core.constant.SystemConstants;
import xin.nick.common.core.util.UserIdUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * mdc 日志配置拦截器
 *
 * @author Nick
 * @since 2022/1/27
 */
@Slf4j
@Component
public class MdcInterceptor implements HandlerInterceptor {

    /**
     * 进入前处理添加MDC的 requestId
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  处理器
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 添加MDC
        String requestId = IdUtil.fastSimpleUUID();
        Long userId = UserIdUtil.getUserIdNotCheck();
        MDC.put(SystemConstants.REQUEST_ID, requestId);
        MDC.put(SystemConstants.USER_ID, String.valueOf(userId));

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MDC.remove(SystemConstants.REQUEST_ID);
        MDC.remove(SystemConstants.USER_ID);
    }
}
